package yb.ecp.fast.user.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;
import yb.ecp.fast.user.dao.entity.DepartmentDO;
import yb.ecp.fast.user.dao.entity.WorkspaceDO;
import yb.ecp.fast.user.dao.mapper.DepartmentMapper;
import yb.ecp.fast.user.dao.mapper.WorkspaceMapper;
import yb.ecp.fast.user.infra.AuthConstant;
import yb.ecp.fast.user.infra.ErrorCode;
import yb.ecp.fast.user.service.VO.ProfileVO;
import yb.ecp.fast.user.service.VO.RoleVO;
import yb.ecp.fast.user.service.VO.TemplateVO;
import yb.ecp.fast.user.service.VO.WorkspaceVO;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiChangjiang on 2017/12/27 0027.
 */
@Service
public class WorkspaceService {
    @Autowired
    WorkspaceMapper workspaceMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private ProfileService profileService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ScepterService scepterService;
    /**
     * 默认admin管理员id
     */
    @Value("${role.admin.roleId}")
    private String roleAdminId;


    /**
     * 查询所有工作空间
     *
     * @return
     */
    public List<WorkspaceVO> queryList() {
        List<WorkspaceDO> workspaceDOs;
        List<WorkspaceVO> workspaceVOs = new ArrayList<>();

        workspaceDOs = workspaceMapper.queryList();

        for (WorkspaceDO workspaceDO : workspaceDOs) {
            WorkspaceVO workspaceVO = new WorkspaceVO();
            BeanUtils.copyProperties(workspaceDO, workspaceVO);
            workspaceVOs.add(workspaceVO);
        }
        return workspaceVOs;
    }

    /**
     * 查询详情
     *
     * @param id String
     * @return WorkspaceVO
     */
    public WorkspaceVO item(String id) {
        WorkspaceVO workspaceVO = new WorkspaceVO();
        WorkspaceDO workspaceDO;
        workspaceDO = workspaceMapper.selectById(id);

        BeanUtils.copyProperties(workspaceDO, workspaceVO);

        return workspaceVO;
    }

    /**
     * 增加工作空间
     *
     * @param workspaceVO WorkspaceVO
     * @return ErrorCode
     */
    public ErrorCode insert(WorkspaceVO workspaceVO) throws Exception {
        WorkspaceDO workspaceDO = new WorkspaceDO();

        BeanUtils.copyProperties(workspaceVO, workspaceDO);

        //增加工作空间
        int ret = workspaceMapper.insert(workspaceDO);

        if (0 >= ret) {
            LogHelper.error("添加工作空间步骤错误！", ErrorCode.FailedToInsertRecord.getCode());
            return ErrorCode.FailedToInsertRecord;
        }

        //添加默认角色
        RoleVO roleVO = new RoleVO();
        roleVO.setSpaceId(workspaceDO.getId());
        roleVO.setName(AuthConstant.INIT_ROLE_NAME);
        ErrorCode roleResult = scepterService.addRole(roleVO, new Ref<>(""));
        if (roleResult.getCode() != ErrorCode.Success.getCode()) {
            return roleResult;
        }
        return addDefaultUser(workspaceVO);
    }


    /**
     * 批量删除工作空间
     *
     * @param ids 批量删除的ID
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode removeByIds(List<String> ids) {
        List<String> result = checkWorkspace(ids);

        if (ListUtil.isNullOrEmpty(result)) {
            result = new ArrayList<>();
            for (String id : ids) {
                int ret = workspaceMapper.removeById(id);

                if (0 >= ret) {
                    result.add(id);
                }
            }

        }

        if (ListUtil.isNullOrEmpty(result)) {
            return ErrorCode.Success;
        } else {
            LogHelper.debug("工作空间删除失败！");
            return ErrorCode.FailedToRemoveRecord;
        }
    }

    /**
     * 修改工作空间信息
     *
     * @param workspaceVO WorkspaceVO
     * @return ErrorCode
     */
    public ErrorCode update(WorkspaceVO workspaceVO) {
        WorkspaceDO workspaceDO = new WorkspaceDO();

        BeanUtils.copyProperties(workspaceVO, workspaceDO);

        int ret = workspaceMapper.updateById(workspaceDO);

        if (0 >= ret) {
            return ErrorCode.FailedToUpdateRecord;
        }

        return ErrorCode.Success;
    }


    /**
     * 校验工作空间是否被使用
     *
     * @param ids 工作空间ID
     * @return 如果被使用，则返回FALSE
     */
    private List<String> checkWorkspace(List<String> ids) {
        List<String> result = new ArrayList<>();

        for (String id : ids) {
            List<DepartmentDO> departmentDOs;
            DepartmentDO departmentDO = new DepartmentDO();
            departmentDO.setSpaceId(id);
            departmentDOs = departmentMapper.queryDeptList(departmentDO);

            if (!ListUtil.isNullOrEmpty(departmentDOs)) {
                result.add(id);
            }
        }
        return result;
    }

    /**
     * 根据工作空间ID查询该工作空间下的权限集合
     *
     * @param workspaceId String
     * @return List
     */
    public List<Integer> queryAuthsByWorkspace(String workspaceId) {
        //查询工作空间对应的模板ID
        WorkspaceDO workspaceDO = workspaceMapper.selectById(workspaceId);

        if (null == workspaceDO) {
            return new ArrayList<>();
        }
        TemplateVO templateVO = templateService.selectById(workspaceDO.getTempId());

        if (null == templateVO) {
            return new ArrayList<>();
        }

        List<Integer> auths = templateService.queryAuthByTemplate(templateVO.getId());

        return auths;
    }

    /**
     * 添加工作空间默认管理员用户<br />
     * 用户登录名为空则用workspaceID作为登录名<br />
     * 密码为空，则使用默认密码<br />
     * 关联角色为管理员角色（读取配置，默认为1）<br />
     * 组织机构ID为一级部门的父级ID（默认为0）
     *
     * @param workspaceVO WorkspaceVO
     * @return ErrorCode
     * @throws Exception Exception
     */
    private ErrorCode addDefaultUser(WorkspaceVO workspaceVO) throws Exception {
        //增加默认管理员与角色信息
        List<String> roleIds = new ArrayList<String>();
        roleIds.add(roleAdminId);
        if (StringUtil.isNullOrEmpty(workspaceVO.getAccount())) {
            return doAddDefaultUser(workspaceVO, roleIds, "管理员", workspaceVO.getId());
        } else {
            ErrorCode r = doAddDefaultUser(workspaceVO, roleIds, "默认管理员", workspaceVO.getId());
            if (r.getCode() == 0) {
                doAddDefaultUserByBusiness(workspaceVO, roleIds);
            }
            return r;
        }
    }

    private void doAddDefaultUserByBusiness(WorkspaceVO workspaceVO, List<String> roleIds) {
        LogHelper.debug("根据erp编码生成管理员账户" + workspaceVO.getAccount());
        if (workspaceVO.getAccount().contains(";")) {
            String[] accounts = workspaceVO.getAccount().split(";");
            for (String s : accounts) {
                if (StringUtils.isNoneBlank(s)) {
                    try {
                        doAddDefaultUser(workspaceVO, roleIds, s, s);
                    } catch (Exception e) {
                        LogHelper.error(s + "添加默认管理员账号（根据ERP编号）失败！", ErrorCode.Failure.getCode());
                    }
                }
            }
        } else {
            try {
                doAddDefaultUser(workspaceVO, roleIds,  workspaceVO.getAccount(), workspaceVO.getAccount());
            } catch (Exception e) {
                LogHelper.error("添加默认管理员账号（根据ERP编号）失败！", ErrorCode.Failure.getCode());
            }
        }
    }

    private ErrorCode doAddDefaultUser(WorkspaceVO workspaceVO, List<String> roleIds, String adminName, String loginName) throws Exception {
        ProfileVO profileVO = new ProfileVO();
        profileVO.setLoginName(loginName);
        profileVO.setName(adminName);
        profileVO.setRoleIds(roleIds);
        profileVO.setPassword(workspaceVO.getPassword());
        profileVO.setSpaceId(workspaceVO.getId());
        profileVO.setDeptId(AuthConstant.DEFAULT_PARENT_DEPT_ID);
        ErrorCode addUser = profileService.insert(profileVO, new Ref<>(""));
        if (addUser.getCode() != 0) {
            return addUser;
        }
        return ErrorCode.Success;
    }

    /**
     * 修改工作空间的权限模板
     *
     * @param workspaceId
     * @param templateId
     * @return
     */
    public ErrorCode updateTemplate(String workspaceId, String templateId) {
        WorkspaceVO workspaceVO = new WorkspaceVO();

        workspaceVO.setId(workspaceId);
        workspaceVO.setTempId(templateId);

        ErrorCode updateCode = update(workspaceVO);

        if (updateCode != ErrorCode.Success) {
            LogHelper.error("修改工作空间的权限模板操作失败！", updateCode.getCode());
            return updateCode;
        }

        //修改权限模板成功之后，重置工作空间下所有角色与auth、menu的关联
        return roleService.releaseByWorkspace(workspaceId);
    }

    /**
     * 删除企业工作空间<br>
     * 删除企业成功之后，删除企业工作空间<br>
     * 由于企业是逻辑删除，避免
     *
     * @param workspaceId remove
     * @return ErrorCode
     */
    public ErrorCode remove(String workspaceId) {
        workspaceMapper.removeById(workspaceId);
        return ErrorCode.Success;
    }

    /**
     * 锁定工作空间
     *
     * @param workspaceId
     * @return
     */
    public ErrorCode lock(String workspaceId) {
        WorkspaceDO workspaceDO = new WorkspaceDO();
        workspaceDO.setId(workspaceId);
        workspaceDO.setStatus("1");
        workspaceMapper.updateById(workspaceDO);
        return ErrorCode.Success;
    }

    /**
     * 解锁工作空间
     *
     * @param workspaceId
     * @return
     */
    public ErrorCode unlock(String workspaceId) {
        WorkspaceDO workspaceDO = new WorkspaceDO();
        workspaceDO.setId(workspaceId);
        workspaceDO.setStatus("0");
        workspaceMapper.updateById(workspaceDO);
        return ErrorCode.Success;
    }

}
